package com.ssyt.yt1.day29.net;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;

/**
 * <pre>
 * URL与URI的区别？
 * 1、URL：uniform resource locator，统一资源定位器，通常指的是定位互联网资源，如:http://www.baidu.com/index.html
 * 2、URI：uniform resource identifier，统一资源标识符，包含本地资源和互联网资源（URL），如:file:///C:/Users/Administrator/Desktop/HTML.html
 * 
 * 注：URL属于URI！
 * </pre>
 *
 * @author Hsu.
 * @since 2016年1月5日
 */
public class URLDemo {

	/**
	 * openStream
	 * 
	 * @throws IOException
	 */
	public static void test1() throws IOException {
		// 协议 + 主机 + 端口 + 路径/资源
		URL url = new URL("http://www.baidu.com:80/index.html");
		System.out.println("协议：" + url.getProtocol());
		System.out.println("主机：" + url.getHost());
		System.out.println("端口：" + url.getPort());
		System.out.println("路径/资源：" + url.getFile());

		InputStream inputStream = url.openStream();
		Scanner scanner = null;
		try {
			scanner = new Scanner(inputStream);
			while (scanner.hasNext()) {
				System.out.println(scanner.nextLine());
			}
		} finally {
			if (scanner != null) {
				scanner.close();
			}
		}
	}

	/**
	 * openConnection()返回URLConnection
	 * 
	 * @throws IOException
	 */
	public static void test2() throws IOException {
		URL url = new URL("http://www.mi.com:80");
		URLConnection urlConnection = url.openConnection();
		System.out.println("响应内容大小：" + urlConnection.getContentLength());
		System.out.println("响应内容类型：" + urlConnection.getContentType());
		System.out.println("响应时间：" + urlConnection.getDate());
	}

	/**
	 * openConnection()返回URLConnection，强转为HttpURLConnection<br>
	 * 在开发中通常使用HttpURLConnection：多了一些方法：setRequestMethod()、getResponseCode()...
	 * 
	 * @throws IOException
	 */
	public static void test3() throws IOException {
		URL url = new URL("http://www.mi.com:80");
		HttpURLConnection httpURLConnection = (HttpURLConnection) url
				.openConnection();
		// 设置请求方式
		httpURLConnection.setRequestMethod("GET");
		// 连接超时设置
		httpURLConnection.setConnectTimeout(3000);

		System.out.println("响应内容大小：" + httpURLConnection.getContentLength());
		System.out.println("响应内容类型：" + httpURLConnection.getContentType());
		System.out.println("响应时间：" + httpURLConnection.getDate());
		// 200：请求响应成功
		// 404：网页不存在
		// 500：服务器内部错误
		System.out.println("HTTP状态码：" + httpURLConnection.getResponseCode());
		System.out.println("请求方式：" + httpURLConnection.getRequestMethod());
	}

	public static void main(String[] args) throws IOException {
		// test1();
		// test2();
		test3();
	}
}
